package com.chen.winnerframework.util;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import cn.hutool.core.io.IoUtil;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Collection;
import java.util.List;

/**
 * excel 工具类
 *
 * @author chengy
 * @date 2022/11/04
 */
public class ExcelUtil {

    /**
     * 通用导入方法
     *
     * @param file      文件
     * @param pojoClass 实体类
     * @return 实体集合
     */
    public static <T> List<T> importExcel(MultipartFile file, Class<T> pojoClass) {
        ImportParams params = new ImportParams();
        params.setTitleRows(1); //去掉标题行
        try {
            return ExcelImportUtil.importExcel(file.getInputStream(), pojoClass, params);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 通用导出方法
     *
     * @param response  响应
     * @param filename  文件名
     * @param pojoClass 实体类
     * @param data      实体数据
     */
    public static void exportExcel(HttpServletResponse response, String filename, Class<?> pojoClass, Collection<?> data) {
        ExportParams params = new ExportParams(filename, filename, ExcelType.XSSF);
        Workbook workbook = ExcelExportUtil.exportExcel(params, pojoClass, data);
        ServletOutputStream outputStream = null;
        try {
            response.setCharacterEncoding("UTF-8");
            response.setHeader("content-type", "application/vnd.ms-excel");
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
            outputStream = response.getOutputStream();
            workbook.write(outputStream);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoUtil.close(outputStream);
        }
    }

}
